<?php
if (!function_exists('sqlConnect'))
{ // check if function already defined to avoid the (function redeclared error)

    /**
     * automated function to connect to mysql database that takes default arguments to save the programmer
     * having to refill parameters on every call
     * @version 1.0 (stable)
     * @author Ronin
     * @param string $sServer [optional] mysql server address
     * @param string $sServerUser [optional] mysql server user name
     * @param string $sServerPass [optional] mysql server pass word
     * @return MySQLlinkIdentifier on failure the function does not return instead it dies reporting mysql_error()
     */

    function sqlConnect($sServer = "localhost", $sServerUser = "root", $sServerPass = "")
    {
        $sqlConn = mysql_connect($sServer, $sServerUser, $sServerPass, true) or die(mysql_error());
        mysql_select_db("mydb", $sqlConn) or die(mysql_error());
        return $sqlConn;
    }

}

if (!function_exists("iInsert"))
{  // check if function already defined to avoid the (function redeclared error)

    /**
     * Inserts a row into the database avoiding sql injection security risks, the function also connects to mysql server
     * automatically so no need to establish a connection first
     * @author Ronin
     * @version 1.0.1 (beta)
     * @param string $sTable name of table to insert the record into
     * @param associative_array $arrValues an associative array with the following format.<br> 
     * keys: the column names to insert in the table<br> 
     * Values: values for each column to insert<br>
     * @example insertRow("comment",array('commentor_id'=>1,'span_id'=>5,'version_id'=>1,'text'=>'hello world'));
     * @return int,string function returns 1  indicating success or a string containing the query that was sent to
     * the database indicating failure, the returned string is for debugging purposes
     */

    function iInsert($sTable, $arrValues)
    {
        if (!is_string($sTable))
        {
            trigger_error("Function 'insertRow' expects '\$sTable' to be a string", E_USER_ERROR);
            return;
        }
        if (!is_array($arrValues))
        {
            trigger_error("Function 'insertRow' expects '\$arrValues' to be an array", E_USER_ERROR);
            return;
        }
        $sqlCon = sqlConnect();
        $sQuery = "INSERT INTO " . $sTable . "(";
        $arrKeys = array_keys($arrValues);
        $sQuery .= implode(",", $arrKeys) . ")" . " VALUES (";
        $len = count($arrKeys);
        $sQuery.="'" . mysql_real_escape_string($arrValues[$arrKeys[0]], $sqlCon) . "'";
        for ($i = 1; $i < $len; $i++)
        {
            $sQuery.=",'" . mysql_real_escape_string($arrValues[$arrKeys[$i]], $sqlCon) . "'";
        }
        $sQuery.=")";
        if (mysql_query($sQuery, $sqlCon))
            return 1;
        else
            return $sQuery . "\n" . mysql_error();
    }

}
if (!function_exists("rsSelect"))
{ // check if function already defined to avoid the (function redeclared error)

    /**
     *  This function acts as an alias for a mysql select statement, it takes care
     * of establishing a connection to the mysql server and securing the input against sql injection attacks before executing the query as
     * well as checking if the resulting resource is valid before returning it
     * @author Ronin
     * @version 1.0.2 (alpha)
     * @param string|array $arrCols name of the column or the array of columns to select
     * @param string|array $arrTables [optional] name of the table or the array of tables to select from
     * @param array $arrConditions [optional] an array of WHERE clause conditions in the following format:<br>
     * {'condition along with operator',value,'if more conditions exist then a bitwise operator if a certain ordering is required
     * then the complete order statement else no element is necessary'}
     * @param string $sJoinConditions [optional] [untested] a string representing any special join statements like inner join, left join or outer join
     * including the table names to be joined, if this parameter is used then the user has to pass $arrConditions as well even if there are no
     * WHERE clause conditions
     * @example simple:<br> $resultset=rsSelect("comment_id","comment",array("comment_id=",1))<br>
     * complex:<br>   $resultset=rsSelect(array('m.member_id','m.first_name'),
     * array('member m','comment c'),
     * array('c.commentor_id=','E__m.member_id','AND','m.email=','lostsamurai@ovi.com','ORDER BY m.member_id DESC'),
     * "Inner join m,c")
     * The previous complex example demostrates the use of the prefix 'E__' which marks the string for escaping
     * since m.member_id is not a variable name or a plain string and should be regarded as a column name, the use of the prefix 'E__'
     * tells the function not to add quotations around this variable before sending the query to mysql server
     * @return resultset|string in case the function was successful a resource resultset is returned otherwise a string
     * is returned containing the query that was sent to the database along with the mysql_error() output
     */

    function rsSelect($arrCols, $arrTables = NULL, $arrConditions = NULL, $sJoinConditions = NULL)
    {
        if ($arrConditions !== NULL && !is_array($arrConditions))
        {
            trigger_error("Function select expects '\$arrConditions' to be an array", E_USER_ERROR);
            return;
        }
        if (!is_array($arrCols) && !is_string($arrCols))
        {
            trigger_error("Function select expects '\$arrCols' to be either an array or a string", E_USER_ERROR);
            return;
        }
        if ($arrTables !== NULL && !is_array($arrTables) && !is_string($arrTables))
        {
            trigger_error("Function select expects '\$arrTables' to be either an array or a string", E_USER_ERROR);
            return;
        }
        if ($sJoinConditions !== NULL && !is_string($sJoinConditions))
        {
            trigger_error("Function select expects '\$JoinConditions' to be a string", E_USER_ERROR);
            return;
        }
        $sqlCon = sqlConnect();
        $sQuery = "SELECT ";
        if (is_string($arrCols))
        {
            $sQuery.=$arrCols;
        }
        else
        {
            $sQuery.=implode(",", $arrCols);
        }

        if ($arrTables !== NULL)
        {
            $sQuery.=" FROM ";
            if (is_string($arrTables))
            {
                $sQuery.= $arrTables . " ";
            }
            else
            {
                $sQuery.=implode(",", $arrTables) . " ";
            }
        }
        if ($sJoinConditions !== NULL)
        {
            $sQuery.=$sJoinConditions . " ";
        }
        if ($arrConditions !== NULL)
        {
            $sQuery.="WHERE ";
            $len = count($arrConditions);
            for ($i = 0; $i < $len; $i++)
            {
                $sQuery.= $arrConditions[$i];
                $i++;
                if (strpos($arrConditions[$i], "E__") === 0)
                {
                    $sQuery.= mysql_real_escape_string(substr($arrConditions[$i], 3), $sqlCon) . " ";
                }
                else
                {
                    $sQuery.="'" . mysql_real_escape_string($arrConditions[$i], $sqlCon) . "'" . " ";
                }
                $i++;
                if ($i >= $len)
                    break;
                else
                    $sQuery.=$arrConditions[$i] . " ";
            }
        }
        $rsResult = mysql_query($sQuery, $sqlCon);
        if (!$rsResult)
            return $sQuery . "\n" . mysql_error();
        else
            return $rsResult;
    }

}

if (!function_exists("iUpdate"))
{

    /**
     * This function acts as an alias for a mysql update statement, it takes care
     * of establishing a connection to the mysql server and securing the input against sql injection attacks before executing the query as
     * @author Ronin
     * @version 1.0 (alpha)
     * @param string $sTable name of the table to update
     * @param associative_array $arrSet [optional] an associative array containing the columns to update along with the update value in the following format<br>
     * key: column to update
     * value: the new value
     * @param array $arrConditions an array of WHERE clause conditions to apply in the following format:<br>
     * {'condition along with operator',value,'if more conditions exist then a bitwise operator else no element is necessary'}
     * @return int,string the function returns 1 on success but on failure it shows the mysql_error() along with
     * the actual query that was sent to mysql server for debugging purposes 
     */
    function iUpdate($sTable, $arrSet, $arrConditions = NULL)
    {
        if (!is_string($sTable))
        {
            trigger_error("Function update expects parameter '\$sTable' to be string", E_USER_ERROR);
            return;
        }
        if (!is_string($arrSet) && !is_array($arrSet))
        {
            trigger_error("Function update expects parameter '\$arrSet' to be string or array", E_USER_ERROR);
            return;
        }
        if ($arrConditions !== NULL && !is_array($arrConditions))
        {
            trigger_error("Function update expects parameter '\$arrConditions' to be array", E_USER_ERROR);
            return;
        }
        $sqlCon = sqlConnect();
        $sQuery = "UPDATE " . $sTable . " SET ";
        $arrkeys = array_keys($arrSet);
        $len = count($arrkeys);
        $sQuery.=$arrkeys[0] . "='" . mysql_real_escape_string($arrSet[$arrkeys[0]], $sqlCon) . "'";
        for ($i = 1; $i < $len; $i++)
        {
            $sQuery.="," . $arrkeys[$i] . "='" . mysql_real_escape_string($arrSet[$arrkeys[$i]], $sqlCon) . "'";
        }
        if ($arrConditions !== NULL)
        {
            $sQuery.=" WHERE ";
            $len = count($arrConditions);
            for ($i = 0; $i < $len; $i++)
            {
                $sQuery.=$arrConditions[$i];
                $i++;
                if (strpos($arrConditions[$i], "E__") === 0)
                {
                    $sQuery.=mysql_real_escape_string(substr($arrConditions[$i], 3), $sqlCon) . " ";
                }
                else
                {
                    $sQuery.="'" . mysql_real_escape_string($arrConditions[$i], $sqlCon) . "' ";
                }
                $i++;
                if ($i >= $len)
                    break;
                else
                {
                    $sQuery.=$arrConditions[$i] . " ";
                }
            }
        }
        if (!mysql_query($sQuery, $sqlCon))
            return $sQuery . "\n" . mysql_error();
        else
            return 1;
    }

}

if (!function_exists("bIsAuthor"))
{

    /**
     * This function checks if a certain member is the author of a paper by using the version
     * id to acquire the paper id and then test to see if the supplied member is the author for
     * it
     * @author Ronin
     * @version 1.0 (alpha)
     * @param int $member_id   id of the member to test against
     * @param int $version_id the version id of the paper to check
     * @return boolean,string the function returns a boolean value indicating if the member is indeed the author or not or a string value indicating
     * the failure of one of the internal queries
     */
    function bIsAuthor($member_id, $version_id)
    {
        $rsPaper = rsSelect("paper_id", "version", array("version_id=", $version_id));
        if (!is_string($rsPaper))
        {
            $row = mysql_fetch_assoc($rsPaper);
            $paper_id = $row['paper_id'];
            $rsAuthor = rsSelect("author_id", "paper", array("paper_id=", $paper_id));
            if (!is_string($rsAuthor))
            {
                $row = mysql_fetch_assoc($rsAuthor);
                $author_id = $row['author_id'];
                if ($author_id == $member_id)
                    return true;
                else
                    return false;
            }
            else
                return $rsAuthor;
        }
        else
            return $rsPaper;
    }

}

if (!function_exists("bIsOrganizer"))
{
    /**
     *This function checks if the supplied member is registered as an organizer in the supllied conference
     * @author Ronin
     * @version 1.0 (alpha)
     * @param int $member_id the id of the member to test for
     * @param int $conference_id the id of the conference to test against
     * @return boolean,string the function returns a boolean value indicating if the member is an organizer in the supplied conference or not
     * or a string if any of the internal queries fail
     */
    function bIsOrganizer($member_id, $conference_id)
    {
        $rsPrivilages = rsSelect("privileges_id", "privileges", array("role=", "organizer"));
        if (is_string($rsPrivilages))
            return $rsPrivilages;
        else
        {
            $row = mysql_fetch_assoc($rsPrivilages);
            $iOrganizer = $row['privileges_id'];
            $rsOrganizer = rsSelect("*", "member_privileges", array("member_id=", $member_id, "AND", "privileges_id=", $iOrganizer, "AND", "conference_id=", $_GET['conference_id']));
            if (is_string($rsOrganizer))
                return $rsOrganizer;
            else
            {
                if (mysql_num_rows($rsOrganizer) > 0)
                    return true;
                else
                    return false;
            }
        }
    }

}

if (!function_exists("bIsReviewer"))
{
    /**
     *The function checks if the supplied member is assiged to the supplied paper in the supplied conference
     * @author Ronin
     * @version 1.0 (alpha)
     * @param int $member_id id of the member to test for
     * @param int $conference_id id of the conference to test the member is assigned to
     * @param int $paper_id id of the paper that is registered under the supplied conference to test if the user is assigned to it
     * @return boolean,string the function returns a boolean value indicating if the supplied member is indeed assigned to the conference and the paper given in the 
     * function arguments or a string if any of the internal queries fail 
     */
    function bIsReviewer($member_id, $conference_id, $paper_id)
    {
        $rsReviewer = rsSelect("*", "assigned_papers", array("member_id=", $member_id, "AND", "conference_id=", $conference_id, "AND", "paper_id=", $paper_id));
        if (is_string($rsReviewer))
            return $rsReviewer;
        else
        {
            if (mysql_num_rows($rsReviewer) > 0)
                return true;
            else
                return false;
        }
    }

}
if (!function_exists("iReformat"))
{

    /**
     * reformats newly converted html files to exploit every possible pattern used by
     * pdftohtml converter to icrease efficiency
     * @author Ronin
     * @version 1.0.5 (beta)
     * @param int $version_id id of the version to reformat
     * @return int the function returns -1 if the database did not contain any versions
     * with the provided $version_id and 1 if the process was completed successfully
     */
    function iReformat($version_id)
    {
        $sqlConn = sqlConnect();
        $rsResult = rsSelect("path", "version", array('version_id=', $version_id));
        if (mysql_num_rows($rsResult) == 0)
            return -1;
        else
        {
            $row = mysql_fetch_assoc($rsResult);
            $sFilePath = $row['path'];
            $arrInfo = pathinfo($sFilePath);
            $sFilePath = $arrInfo['dirname'] . "/" . $arrInfo['filename'] . ".html";
            $sHtml = file_get_contents($sFilePath);
            $iCount = 1;
            $sReplaced_DIV = preg_replace('/<DIV id="div1"/', '<DIV ', $sHtml, $iCount);
            $sReplaced_DIV = preg_replace('/<DIV /', '<DIV id="div1" ', $sReplaced_DIV, $iCount);
            $iSpans = substr_count($sReplaced_DIV, '<span ');
            $arrIds = array();
            $arrSpans = array();
            for ($i = 0; $i < $iSpans; $i++)
            {
                $iCurr = $i + 1;
                $arrIds[$i] = '<span id="' . $iCurr . '" class';
                $arrSpans[$i] = '/<span class/';
            }
            $sReplaced_DIV_SPAN = preg_replace($arrSpans, $arrIds, $sReplaced_DIV, $iCount);
            $fpHandle = fopen($sFilePath, "w");
            fwrite($fpHandle, $sReplaced_DIV_SPAN);
            fflush($fpHandle);
            fclose($fpHandle);
            return 1;
        }
    }

}
?>